package com.xwdeshj.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xwdeshj.entity.XwFarmMerchanttype;
import com.xwdeshj.repository.XwFarmMerchanttypeRepository;
import com.xwdeshj.service.XwFarmMerchanttypeService;
import com.xwdeshj.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by BKWJA on 2018/12/20.
 * 农家乐商户类型管理实现类
 */
@Service("xwFarmMerchanttypeService")
@Slf4j
public class XwFarmMerchanttypeServiceImpl implements XwFarmMerchanttypeService {

    @Autowired
    private XwFarmMerchanttypeRepository xwFarmMerchanttypeRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Sid sid;

    @Override
    public JSONObject getfarmtypelist(Integer pageindex, Integer pagesize, String starttime,
                                      String endtime, String sortfild, String sortway) {
        JSONObject result = new JSONObject();
        String sql = "select farmType_Merid,farmType_encryptId,farmType_desc,farmType_updatetime,farmType_createtime from xw_farm_merchanttype ";
        StringBuffer sb = new StringBuffer();
        sb.append(" 1=1 ");
        if(!starttime.equals("")){
            starttime += " 00.00.01";
            endtime += " 23.59.59";
            sb.append(" and farmType_createtime >= '"+starttime+"' and farmType_createtime <= '"+ endtime + "' ");
        }
        //排序
        if (!sortfild.equals("")){
            sb.append(" order by "+sortfild+" " +sortway + " ");
        }
        try {
            sql = sql + " where " +sb.toString() + " limit "+ (pageindex-1)*pagesize + "," + pagesize;
            //分页SQL
            String sql2 = "select count(*) from xw_farm_merchanttype where " + sb.toString();
            SqlRowSet rs = jdbcTemplate.queryForRowSet(sql);
            SqlRowSet rs2 = jdbcTemplate.queryForRowSet(sql2);
            result.put("status",0);
            result.put("msg","ok");
            while (rs2.next()){
                Integer count = rs2.getInt(1);
                result.put("recordcount",count);
                if (count%pagesize == 0){
                    result.put("pagecount",count/pagesize);
                }else {
                    result.put("pagecount",count/pagesize + 1);
                }
            }
            JSONArray jsonArray = new JSONArray();
            while (rs.next()){
                JSONObject object = new JSONObject();
                object.put("farmType_Merid",rs.getString("farmType_Merid"));
                object.put("farmType_encryptId",rs.getString("farmType_encryptId"));
                object.put("farmType_desc",(rs.getString("farmType_desc")==null?"":rs.getString("farmType_desc")));
                object.put("farmType_updatetime", DateUtil.DateToString(rs.getDate("farmType_updatetime")));
                object.put("farmType_createtime",DateUtil.DateToString(rs.getDate("farmType_createtime")));
                jsonArray.add(object);
            }
            result.put("list",jsonArray);
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg",e);
        }
        System.out.println("getfarmtypelist:"+result.toString());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject updatefarmtype(String farmType_encryptId, String farmType_desc) {
        JSONObject result = new JSONObject();

        if(farmType_encryptId.equals("")){
            XwFarmMerchanttype fartype = new XwFarmMerchanttype();
            fartype.setFarmtypeEncryptid(sid.nextShort());
            fartype.setFarmtypeDesc(farmType_desc);
            fartype.setFarmtypeCreatetime(new Date());
            fartype.setFarmtypeUpdatetime(new Date());
            try {
                xwFarmMerchanttypeRepository.save(fartype);
                result.put("status",0);
                result.put("msg","ok");
            }catch (Exception e){
                e.printStackTrace();
                result.put("status",500);
                result.put("msg",e);
            }
        }else {
            XwFarmMerchanttype farMartype = xwFarmMerchanttypeRepository.findByFarmtypeEncryptid(farmType_encryptId);

            if (farMartype != null){
                farMartype.setFarmtypeDesc(farmType_desc);
                farMartype.setFarmtypeUpdatetime(new Date());
                try {
                    xwFarmMerchanttypeRepository.save(farMartype);
                    result.put("status",0);
                    result.put("msg","ok");
                }catch (Exception e){
                    e.printStackTrace();
                    result.put("status",500);
                    result.put("msg",e);
                }
            }else {
                result.put("status",500);
                result.put("msg","该记录不存在！");
            }

        }
        System.out.println("updatefarmtype:"+result.toString());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject delfarmtype(String farmType_encryptId) {
        JSONObject result = new JSONObject();
        if(!"".equals(farmType_encryptId) && farmType_encryptId != null){
            try {
                if(farmType_encryptId.indexOf(",") == -1){
                    //单个删除
                   int flag =  xwFarmMerchanttypeRepository.deleteByFarmtypeEncryptid(farmType_encryptId);
                   if(flag == 1){
                       result.put("status",0);
                       result.put("msg","ok");
                   }else {
                       result.put("status",500);
                       result.put("msg","删除失败！");
                   }
                }else {
                    //批量删除
                    int flag = 0;
                    String[] tids = farmType_encryptId.split(",");
                    for (int i = 0; i < tids.length; i++) {
                        flag = xwFarmMerchanttypeRepository.deleteByFarmtypeEncryptid(tids[i]);
                    }
                    if(flag == 1){
                        result.put("status",0);
                        result.put("msg","ok");
                    }else {
                        result.put("status",500);
                        result.put("msg","删除失败！");
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                result.put("status",500);
                result.put("msg",e);
            }

        }else {
            result.put("status",500);
            result.put("msg","farmType_encryptId不能为空！");
        }
        System.out.println("delfarmtype："+result);
        return result;
    }

    @Override
    public JSONObject getAllfarmMertype() {
        JSONObject result = new JSONObject();
        String sql = "select farmType_Merid,farmType_encryptId,farmType_desc from xw_farm_merchanttype order by farmType_createtime ASC";
        try {
            SqlRowSet rs = jdbcTemplate.queryForRowSet(sql);
            JSONArray jsonArray = new JSONArray();
            while (rs.next()){
                JSONObject object = new JSONObject();
                object.put("farmMerId",rs.getString("farmType_Merid"));
                object.put("encryptId",rs.getString("farmType_encryptId"));
                object.put("title",(rs.getString("farmType_desc")==null?"":rs.getString("farmType_desc")));
                jsonArray.add(object);
            }
            result.put("list",jsonArray);
            result.put("status",0);
            result.put("msg","ok");
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg",e);
        }
        System.out.println("getAllfarmMertype："+result.toString());
        return  result;
    }


}
